from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import uuid

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    phone = db.Column(db.String(20), unique=True, nullable=False)
    nickname = db.Column(db.String(50), nullable=False)
    avatar_url = db.Column(db.String(200), nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    last_active = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 关系
    created_circles = db.relationship('Circle', backref='creator', lazy=True, foreign_keys='Circle.creator_id')
    circle_memberships = db.relationship('CircleMember', backref='user', lazy=True)
    locations = db.relationship('Location', backref='user', lazy=True)
    messages = db.relationship('Message', backref='sender', lazy=True)

    def __repr__(self):
        return f'<User {self.nickname}>'

    def to_dict(self):
        return {
            'id': self.id,
            'phone': self.phone,
            'nickname': self.nickname,
            'avatar_url': self.avatar_url,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'last_active': self.last_active.isoformat() if self.last_active else None
        }

class Circle(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text, nullable=True)
    creator_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    invite_code = db.Column(db.String(36), unique=True, nullable=False, default=lambda: str(uuid.uuid4()))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    is_active = db.Column(db.Boolean, default=True)
    
    # 关系
    members = db.relationship('CircleMember', backref='circle', lazy=True, cascade='all, delete-orphan')
    locations = db.relationship('Location', backref='circle', lazy=True)
    messages = db.relationship('Message', backref='circle', lazy=True)

    def __repr__(self):
        return f'<Circle {self.name}>'

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'creator_id': self.creator_id,
            'invite_code': self.invite_code,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'is_active': self.is_active,
            'member_count': len(self.members) if self.members else 0
        }

class CircleMember(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    circle_id = db.Column(db.Integer, db.ForeignKey('circle.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    role = db.Column(db.String(20), default='member')  # 'admin' or 'member'
    joined_at = db.Column(db.DateTime, default=datetime.utcnow)
    is_active = db.Column(db.Boolean, default=True)
    
    # 唯一约束：一个用户在一个圈子中只能有一个成员记录
    __table_args__ = (db.UniqueConstraint('circle_id', 'user_id', name='unique_circle_member'),)

    def __repr__(self):
        return f'<CircleMember circle_id={self.circle_id} user_id={self.user_id}>'

    def to_dict(self):
        return {
            'id': self.id,
            'circle_id': self.circle_id,
            'user_id': self.user_id,
            'role': self.role,
            'joined_at': self.joined_at.isoformat() if self.joined_at else None,
            'is_active': self.is_active
        }

class Location(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    circle_id = db.Column(db.Integer, db.ForeignKey('circle.id'), nullable=False)
    latitude = db.Column(db.Float, nullable=False)
    longitude = db.Column(db.Float, nullable=False)
    accuracy = db.Column(db.Float, nullable=True)  # GPS精度
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<Location user_id={self.user_id} lat={self.latitude} lng={self.longitude}>'

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'circle_id': self.circle_id,
            'latitude': self.latitude,
            'longitude': self.longitude,
            'accuracy': self.accuracy,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None
        }

class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    circle_id = db.Column(db.Integer, db.ForeignKey('circle.id'), nullable=False)
    sender_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    message_type = db.Column(db.String(20), nullable=False)  # 'text', 'image', 'voice'
    content = db.Column(db.Text, nullable=True)  # 文字内容或文件URL
    file_url = db.Column(db.String(500), nullable=True)  # 图片或语音文件URL
    duration = db.Column(db.Integer, nullable=True)  # 语音消息时长（秒）
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<Message {self.message_type} from user_id={self.sender_id}>'

    def to_dict(self):
        return {
            'id': self.id,
            'circle_id': self.circle_id,
            'sender_id': self.sender_id,
            'message_type': self.message_type,
            'content': self.content,
            'file_url': self.file_url,
            'duration': self.duration,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None
        }

